﻿package  
{
	import Base.Loader.SWFLoader;
	import Base.Log.LogManager;
	import Base.Net.*;
	
	import Common.*;
	
	import Events.*;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.ByteArray;
	
	
	/**
	 * ...
	 * @author fox
	 */
	public class LoginUIHandler 
	{
		public var loginUI:LoginUI = null;
		
		public var waitingConnect:Boolean = false;
		public var netSocket:NetSocket = null;
		public var rootSprite:Sprite = null;
		
		public var loader:SWFLoader = null;
		
		public var selectRoleUI:MovieClip = null;
		public var createPlayerUI:MovieClip = null;
		
		public var actionArray:Array = null;
		public var selectID:int = GameDefine.INVALIDID;
		
		public function LoginUIHandler() 
		{
			
		}
		
		public function init( root:Sprite ):void
		{
			actionArray = new Array();
			
			
			rootSprite = root;
			
			loginUI = new LoginUI();
			loginUI.loginButton.addEventListener( MouseEvent.CLICK , onLogin );
			
			rootSprite.addChild( loginUI );
			
			netSocket = GameNetManager.instance.MainNetSocket;
			
			netSocket.addEventListener( NetEvent.CLOSE , onClose );
			netSocket.addEventListener( NetEvent.ERROR , onClose );
			netSocket.addEventListener( NetEvent.CONNECT , onConnect );
			
			NetEvent.registerEvent( GameNetEvent.RECV_LOGIN_ID , onRecvLogin );
			
			loader = new SWFLoader();
			loader.contentLoaderInfo.addEventListener( Event.INIT , onLoad );
			loader.Load( GameDefine.PATHUI + "createPlayer.swf" );
			
			RenderManager.instance.stage.addEventListener( Event.ENTER_FRAME , onFrame );
		}
		
		
		public function clearSelect():void
		{
			for ( var i:int = 0 ; i < actionArray.length ; i++ )
			{
				actionArray[ i ].select = false;
				actionArray[ i ].color = 0;
				actionArray[ i ].setAction( GameAction.STAND , MapDirection.SOUTHWEST );
			}
		}
		
		public function onSelect( event:MouseEvent ):void
		{
			clearSelect();
			
			var a:Array = event.target.name.split( "mc" );
			var i:int = a[ 1 ];
			
			actionArray[ i ].select = true;
			actionArray[ i ].setAction( GameAction.MOVE , MapDirection.SOUTHWEST );
			
			selectID = i;
			
			selectRoleUI.commandButton.visible = true;
		}
		
		
		public function onCOK( event:MouseEvent ):void
		{
			if ( createPlayerUI.nameText.text.length && createPlayerUI.attrTotal == 10 && createPlayerUI.baseTotal == 20 )
			{
				var nameText:ByteArray = new ByteArray();
				nameText.writeUTFBytes( createPlayerUI.nameText.text );
				nameText.length = GameDefine.MAX_NAME;
				
				netSocket.writeShort( GameNetEvent.SEND_CREAT_ROLE_SIZE );
				netSocket.writeShort( GameNetEvent.SEND_CREAT_ROLE_ID );
				netSocket.writeBytes( nameText );
				
				netSocket.writeByte( createPlayerUI.id );
				netSocket.writeByte( createPlayerUI.color );
				netSocket.writeByte( createPlayerUI.eye );
				netSocket.writeByte( createPlayerUI.mouth );
				
				netSocket.writeByte( createPlayerUI.Vitality );
				netSocket.writeByte( createPlayerUI.Strength );
				netSocket.writeByte( createPlayerUI.Toughness );
				netSocket.writeByte( createPlayerUI.Dexterity );
				
				netSocket.writeByte( createPlayerUI.earth );
				netSocket.writeByte( createPlayerUI.water );
				netSocket.writeByte( createPlayerUI.fire );
				netSocket.writeByte( createPlayerUI.wind );
				
				netSocket.Send();
			}
			
			
		}
		
		public function onCBack( event:MouseEvent ):void
		{
			selectRoleUI.visible = true;
			createPlayerUI.visible = false;
		}
		
		public function onSDecide( event:MouseEvent ):void
		{
			selectRoleUI.commandButton.visible = false;
			
			selectRoleUI.visible = false;
			createPlayerUI.visible = true;
			
			createPlayerUI.setData( selectID , actionArray[ selectID ].color );
			
			clearSelect();
		}
		public function onSColor( event:MouseEvent ):void
		{
			actionArray[ selectID ].color++;
			
			if ( actionArray[ selectID ].color > 3 )
			{
				actionArray[ selectID ].color = 0;
			}
			
			actionArray[ selectID ].setID( RoleConfig.instance.getIndex( selectID , actionArray[ selectID ].color , GameDefine.INVALIDID ) );
		}
		public function onSDirection( event:MouseEvent ):void
		{
			actionArray[ selectID ].direct++;
			
			if ( actionArray[ selectID ].direct == MapDirection.DIRECTCOUNT )
			{
				actionArray[ selectID ].direct = 0;
			}
			
			actionArray[ selectID ].setAction( GameAction.MOVE , actionArray[ selectID ].direct );
		}
		
		public function onSCancel( event:MouseEvent ):void
		{
			selectRoleUI.commandButton.visible = false;
			selectID = GameDefine.INVALIDID;
			
			clearSelect();
		}
		
		public function onFrame( e:Event ):void
		{
			for ( var i:int = 0 ; i < actionArray.length ; i++ )
			{
				actionArray[ i ].update( 30 );
			}
		}
		
		
		public function onLoad( event:Event ):void
		{
			var cls:Class = loader.getClass( "SelectRoleUI" );
			selectRoleUI = new cls();
			
			cls = loader.getClass( "CreatePlayerUI" );
			createPlayerUI = new cls();
			
			rootSprite.addChild( selectRoleUI );
			rootSprite.addChild( createPlayerUI );
			
			selectRoleUI.backButton.addEventListener( MouseEvent.CLICK , onBackLogin );
			
			selectRoleUI.commandButton.decideButton.addEventListener( MouseEvent.CLICK , onSDecide );
			selectRoleUI.commandButton.colorButton.addEventListener( MouseEvent.CLICK , onSColor );
			selectRoleUI.commandButton.directionButton.addEventListener( MouseEvent.CLICK , onSDirection);
			selectRoleUI.commandButton.cancelButton.addEventListener( MouseEvent.CLICK , onSCancel );
			
			createPlayerUI.backButton.addEventListener( MouseEvent.CLICK , onCBack );
			createPlayerUI.okButton.addEventListener( MouseEvent.CLICK , onCOK );
			
			selectRoleUI.commandButton.visible = false;
			selectRoleUI.visible = !loginUI.visible;
			createPlayerUI.visible = false;
			
			for ( var i:int = 0 ; i < selectRoleUI.roleArray.length ; i++ )
			{
				var role:LoginRole = new LoginRole();
				role.initRole( selectRoleUI.roleArray[ i ] );
				role.setID( RoleConfig.instance.getIndex( i , 0 , GameDefine.INVALIDID ) );
				role.setAction( GameAction.STAND , MapDirection.SOUTHWEST );
				selectRoleUI.roleArray[ i ].addEventListener( MouseEvent.CLICK , onSelect );
				
				actionArray.push( role );
			}
			
			resize();
		}
		
		public function resize():void
		{
			loginUI.x = RenderManager.instance.stageWidth * 0.5;
			loginUI.y = RenderManager.instance.stageHeight * 0.5;
			
			if ( selectRoleUI )
			{
				selectRoleUI.x = RenderManager.instance.stageWidth * 0.5;
				selectRoleUI.y = RenderManager.instance.stageHeight * 0.5;
			}
			
			if ( createPlayerUI )
			{
				createPlayerUI.x = RenderManager.instance.stageWidth * 0.5;
				createPlayerUI.y = RenderManager.instance.stageHeight * 0.5;
			}
		}
		
		public function release():void
		{
			RenderManager.instance.stage.removeEventListener( Event.ENTER_FRAME , onFrame );
			
			rootSprite.removeChild( loginUI );
			
			loginUI.loginButton.removeEventListener( MouseEvent.CLICK , onLogin );
			loginUI = null;
			
			netSocket.removeEventListener( NetEvent.CLOSE , onClose );
			netSocket.removeEventListener( NetEvent.ERROR , onClose );
			netSocket.removeEventListener( NetEvent.CONNECT , onConnect );
			
			waitingConnect = false;
			rootSprite = null
			netSocket = null;
			
			NetEvent.unRegisterEvent( GameNetEvent.RECV_LOGIN_ID );
		}
		
		
		public function sendConnect():void
		{
			trace( GameDefine.SERVER_HOST , GameDefine.SERVER_PORT );
			netSocket.Connect( GameDefine.SERVER_HOST , GameDefine.SERVER_PORT );
		}
		
		
		public function sendAccountLogin():void
		{
			if ( !loginUI.loginButton.enabled ) 
			{
				return;
			}
			
			var accountText:ByteArray = new ByteArray();
			accountText.writeUTFBytes( loginUI.accountText.text );
			accountText.length = GameDefine.MAX_NAME;
			
			var passwordText:ByteArray = new ByteArray();
			passwordText.writeUTFBytes( loginUI.passwordText.text );
			passwordText.length = GameDefine.MAX_NAME;
			
			netSocket.writeShort( GameNetEvent.SEND_LOGIN_SIZE );
			netSocket.writeShort( GameNetEvent.SEND_LOGIN_ID );
			netSocket.writeBytes( accountText );
			netSocket.writeBytes( passwordText );
			
			if ( loginUI.accountText.text.length || loginUI.passwordText.text.length )
			{
				netSocket.writeInt( 0 );
			}
			else
			{
				netSocket.writeInt( 1 );
			}
			
			
			netSocket.Send();
			
			enableButton( false );
			
			trace( "login server..." );
		}
		
		
		public function enableButton( b:Boolean ):void
		{
			if ( loginUI )
				loginUI.loginButton.enabled = b;
		}
		
		
		public function onBackLogin( event:MouseEvent ):void
		{
			loginUI.visible = true;
			selectRoleUI.visible = false;
			createPlayerUI.visible = false;
			
			selectID = GameDefine.INVALIDID;
			selectRoleUI.commandButton.visible = false;
			clearSelect();
		}
		
		
		public function onLogin( event:MouseEvent ):void
		{
			//var moduleEvent:ModuleEvent = new ModuleEvent( ModuleEvent.LOGINRELEASE );
			//ModuleEventManager.instance.dispatchEvent( moduleEvent );
			
			//return;
			
			MessageBox.Msg( GameDefine.STR_Connect , true );
				
			if ( loginUI.accountText.length == 0 ||
			loginUI.passwordText.length == 0 ) 
			{
				//return;
				//loginUI.accountText.text = "fox";
				//loginUI.passwordText.text = "fox";
				
			}
			
			var netManager:NetSocket = GameNetManager.instance.MainNetSocket;
			
			
			
			
			if ( netManager.isValid() )
			{
				sendAccountLogin();
			}
			else
			{
				if ( waitingConnect ) 
				{
					return;
				}
				
				waitingConnect = true;
				sendConnect();
			}
		}
		
		
		public function onRecvLogin( data:ByteArray ):void
		{
			//Release();
			
			var stage:int = data.readInt();
			
			
			switch( stage )
			{
				case 0:
				{
					MessageBox.unshow();
					
					ActionManager.instance.clear();
					
					if ( loader )
					{
						loader.Release();
					}
					
					var moduleEvent:ModuleEvent = new ModuleEvent( ModuleEvent.LOGINRELEASE );
					ModuleEventManager.instance.dispatchEvent( moduleEvent );
				}
				break;
				case 1:
				{
					MessageBox.Msg( GameDefine.STR_ConnectDown1 );
					LogManager.logOut( "connect error。 " );
					enableButton( true );
				}
				break;
				case 2:
				{
					MessageBox.unshow();
					
					loginUI.visible = false;
					
					if ( selectRoleUI )
					{
						selectRoleUI.visible = true;
					}
					
					enableButton( true );
				}
				break;
			}
			
		}
		
		
		public function onClose( evnet:NetEvent ):void
		{
			// error or close
			
			//if ( waitingConnect ) 
			{
				MessageBox.Msg( GameDefine.STR_ConnectDown );
				
				LogManager.logOut( "connect error or close." );
				
				waitingConnect = false;
				enableButton( true );
			}
			
		}
		
		public function onConnect( event:NetEvent ):void
		{
			if ( waitingConnect ) 
			{
				//var netManager:NetManager = GameManager.instance.MainNetManager;
				
				LogManager.logOut( "connect server." );
				
				waitingConnect = false;
				sendAccountLogin();
			}
			
		}
		
	}
	
}